package com.doctor.windflower_doctor.pop;

import java.io.File;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.activity.BaseActivity;
import com.doctor.windflower_doctor.download.DownloadManager;
import com.doctor.windflower_doctor.download.DownloadService;
import com.doctor.windflower_doctor.entity.DownloadInfo;
import com.doctor.windflower_doctor.util.StringUtil;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;

/**
 * <p>
 * 功能 版本更新
 * </p>
 * 
 * <p>
 * Copyright 掌动乾坤公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年4月8日 上午9:59:25
 * @version 1.0 </br> 最后修改人 无
 * 
 */
public class VersionUpdatePop extends BasePopupWindow {
	private LinearLayout delete_pop_layout;
	private TextView queding_text;
	private TextView quxiao_text;
	private TextView title_text;
	private String url;
	private ProgressDialog pd;
	private String title;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				pd.setProgress((Integer) msg.obj);
				break;
			}
			super.handleMessage(msg);

		}

	};

	public VersionUpdatePop(BaseActivity act, String url) {
		this(act, url, null);
	}

	public VersionUpdatePop(BaseActivity act, String url, String title) {
		super(act, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		this.title = title;
		this.url = url;
	}

	@Override
	protected void setListener() {
		delete_pop_layout.setOnClickListener(this);
		queding_text.setOnClickListener(this);
		quxiao_text.setOnClickListener(this);
	}

	@Override
	protected void findViews() {
		delete_pop_layout = (LinearLayout) findViewById(R.id.delete_pop_layout);
		title_text = (TextView) findViewById(R.id.title_text);
		queding_text = (TextView) findViewById(R.id.queding_text);
		quxiao_text = (TextView) findViewById(R.id.quxiao_text);
		title_text.setText("确定要升级当前版本？");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.palm6.tutorhousekeeper.mpop.BasePopupWindow#onShowPre()
	 */
	@Override
	protected void onShowPre() {

		if (title != null && !TextUtils.isEmpty(title)) {
			title_text.setText(title);
		} else {
			title_text.setText("确定要升级当前版本？");
		}
		super.onShowPre();

	}

	@Override
	protected int getContentViewLayoutId() {

		return R.layout.delete_queren_pop;

	}

	@Override
	protected void initViewDrawableSelectCache() {

	}

	@Override
	protected void onItemClick(View view, PopupWindow pop) {
		switch (view.getId()) {
		case R.id.delete_pop_layout:
			// pop.dismiss();
			break;
		case R.id.queding_text:
			downLoad();
			break;
		case R.id.quxiao_text:
			pop.dismiss();
			break;
		}
	}

	// 安装apk
	protected void installApk(File file) {
		Intent intent = new Intent();
		// 执行动作
		intent.setAction(Intent.ACTION_VIEW);
		// 执行的数据类型
		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");// 编者按：此处Android应为android，否则造成安装不了
		mAct.startActivity(intent);
	}

	public void downLoad() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			pd = new ProgressDialog(mAct);
			pd.setIndeterminate(false);
			pd.setCanceledOnTouchOutside(false);
			pd.setMax(100);
			// String url = "http://download.fengxz.com.cn/doctor.apk";
			String fileName = StringUtil.getUrlFileName(url);
			final String target = Environment.getExternalStorageDirectory() + File.separator + "com.doctor.windflower_doctor" + File.separator
					+ "windflower_doctor.apk";
			// File file = new File(target);
			final File file = new File(Environment.getExternalStorageDirectory() + File.separator + "com.doctor.windflower_doctor", "windflower_doctor.apk");
			final DownloadManager downloadManager = DownloadService.getDownloadManager(mAct);
			try {
				downloadManager.downloadApk(url, fileName, target, true, false, new RequestCallBack<File>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						Toast.makeText(mAct, "下载失败-----" + arg0.getMessage(), Toast.LENGTH_SHORT).show();
						pd.dismiss();
					}

					@Override
					public void onSuccess(ResponseInfo<File> arg0) {
						installApk(file);
						pd.dismiss();
					}

					@Override
					public void onStart() {
						super.onStart();
						LogUtils.e("onStart");
						pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
						pd.setMessage("正在下载更新");
						pd.show();
					}

					@Override
					public void onLoading(long total, long current, boolean isUploading) {

						super.onLoading(total, current, isUploading);
						if (!pd.isShowing()) {
							try {
								LogUtils.e("stopAllDownload");
								downloadManager.stopAllDownload();
								Toast.makeText(mAct, "停止下载", Toast.LENGTH_SHORT).show();
							} catch (DbException e) {

								// TODO Auto-generated catch block
								e.printStackTrace();

							}
						} else {
							Double db = Double.longBitsToDouble(current) / Double.longBitsToDouble(total);
							int num = (int) (db * 100);
							LogUtils.e("VersionUpdatePop--------->onLoading" + current + "---------->" + total + "----%----" + num + "____________" + db);
							Message message = new Message();
							message.what = 1;
							message.obj = num;
							handler.sendMessage(message);
						}
						// pd.setProgress(num);
					}
				});
			} catch (DbException e) {

				e.printStackTrace();

			}
		} else {
			Toast.makeText(mAct, "检测不到内存卡", Toast.LENGTH_SHORT).show();
		}
	}
}
